<?php
/**
 * 商品管理
 */
namespace Merch\Controller;

use Common\Controller\AdminbaseController;

class AdminGoodsController extends AdminbaseController {

    protected $goods_model;
    protected $merch_model;

    function _initialize() {
        parent::_initialize();
        $this->goods_model = D("Merch/MerchGoods");
        $this->merch_model = D("Merch/Merch");
    }

    // 后台商品管理列表
    public function index(){
        $this->_lists(array("goods_status"=>array('neq',-1)));
        $this->display();
    }

    // 商品添加
    public function add(){
        $terms = $this->merch_model->where(array("merch_status"=>array("neq","-1")))->order(array("create_time"=>"desc"))->select();

        $this->assign("terms",$terms);
        $this->display();

    }

    // 商品添加提交
    public function add_post(){

        if (IS_POST) {
            if(empty($_POST['term'])){
                $this->error("请至少选择一个分类！");
            }
            if(!empty($_POST['photos_alt']) && !empty($_POST['photos_url'])){
                foreach ($_POST['photos_url'] as $key=>$url){
                    $photourl=sp_asset_relative_url($url);
                    $_POST['smeta']['photo'][]=array("url"=>$photourl,"alt"=>$_POST['photos_alt'][$key]);
                }
            }
            $_POST['smeta']['thumb'] = sp_asset_relative_url($_POST['smeta']['thumb']);
            $_POST['smeta']['avatar'] = sp_asset_relative_url($_POST['smeta']['avatar']);

            $_POST['post']['update_time']=date("Y-m-d H:i:s",time());

            $merch=I("post.post");
            $merch['mid']=$_POST['term'];
            $merch['goods_pics']=json_encode($_POST['smeta']);
            $merch['goods_content']=htmlspecialchars_decode($merch['goods_content']);

            $result=$this->goods_model->add($merch);

            if ($result) {
                $this->success("添加成功！");
            } else {
                $this->error("添加失败！");
            }

        }
    }

    // 商品编辑
    public function edit(){
        $id=  I("get.id",0,'intval');

        // $term_relationship = M('ActivityRelationships')->where(array("merch_id"=>$id,"status"=>1))->getField("mid",true);
        // $this->_getTermTree($term_relationship);
        $post=$this->goods_model->where("id=$id")->find();
        $terms=$this->merch_model->select();

        $this->assign("post",$post);
        $this->assign("smeta",json_decode($post['goods_pics'],true));
        $this->assign("terms",$terms);
        // $this->assign("term",$term_relationship);
        $this->display();
    }

    // 商品编辑提交
    public function edit_post(){
        if (IS_POST) {
            if(empty($_POST['term'])){
                $this->error("请至少选择一个分类！");
            }
            $post_id=intval($_POST['post']['id']);

            if(!empty($_POST['photos_alt']) && !empty($_POST['photos_url'])){
                foreach ($_POST['photos_url'] as $key=>$url){
                    $photourl=sp_asset_relative_url($url);
                    $_POST['smeta']['photo'][]=array("url"=>$photourl,"alt"=>$_POST['photos_alt'][$key]);
                }
            }
            $_POST['smeta']['thumb'] = sp_asset_relative_url($_POST['smeta']['thumb']);
            $_POST['smeta']['avatar'] = sp_asset_relative_url($_POST['smeta']['avatar']);

            $_POST['post']['update_time']=date("Y-m-d H:i:s",time());
            $merch=I("post.post");
            $merch['mid']=$_POST['term'];
            $merch['goods_pics']=json_encode($_POST['smeta']);
            $merch['goods_content']=htmlspecialchars_decode($merch['goods_content']);

            $result=$this->goods_model->save($merch);

            if ($result!==false) {
                $this->success("保存成功！");
            } else {
                $this->error("保存失败！");
            }
        }
    }

    // 商品排序
    public function listorders() {
        $status = parent::_listorders();
        if ($status) {
            $this->success("排序更新成功！");
        } else {
            $this->error("排序更新失败！");
        }
    }

    /**
     * 商品列表处理方法,根据不同条件显示不同的列表
     * @param array $where 查询条件
     */
    private function _lists($where=array()){
        $mid=I('request.term',0,'intval');

        // $where['merch_type']=array(array('eq',1),array('exp','IS NULL'),'OR');

        if(!empty($mid)){
            $where['b.mid']=$mid;
            $term=$this->goods_model->where(array('mid'=>$mid))->find();
            $this->assign("term",$term);
        }

        $start_time=I('request.start_time');
        if(!empty($start_time)){
            $where['create_time']=array(
                array('EGT',$start_time)
            );
        }

        $end_time=I('request.end_time');
        if(!empty($end_time)){
            if(empty($where['create_time'])){
                $where['create_time']=array();
            }
            array_push($where['create_time'], array('ELT',$end_time));
        }

        $keyword=I('request.keyword');
        if(!empty($keyword)){
            $where['goods_name']=array('like',"%$keyword%");
        }

        $this->goods_model
        ->alias("a")
        ->where($where);

        $count=$this->goods_model->count();

        $page = $this->page($count, 20);

        $this->goods_model
        ->alias("a")
        ->where($where)
        ->limit($page->firstRow , $page->listRows)
        ->order("a.create_time DESC");

        $posts=$this->goods_model->select();

        $this->assign("page", $page->show('Admin'));
        $this->assign("formget",array_merge($_GET,$_POST));
        $this->assign("posts",$posts);
    }

    // 获取商品分类树结构 select 形式
    private function _getTree(){
        $mid=empty($_REQUEST['term'])?0:intval($_REQUEST['term']);
        $result = $this->merch_model->where(array("status"=>array("neq","-1")))->order(array("create_time"=>"desc"))->select();

        $tree = new \Tree();
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        foreach ($result as $r) {
            $r['str_manage'] = '<a href="' . U("AdminCategory/add", array("parent" => $r['mid'])) . '">添加子类</a> | <a href="' . U("AdminCategory/edit", array("id" => $r['mid'])) . '">修改</a> | <a class="js-ajax-delete" href="' . U("AdminCategory/delete", array("id" => $r['mid'])) . '">删除</a> ';
            $r['visit'] = "<a href='#'>访问</a>";
            $r['taxonomys'] = $this->taxonomys[$r['taxonomy']];
            $r['id']=$r['mid'];
            $r['parentid']=$r['parent'];
            $r['selected']=$mid==$r['mid']?"selected":"";
            $array[] = $r;
        }

        $tree->init($array);
        $str="<option value='\$id' \$selected>\$spacer\$name</option>";
        $taxonomys = $tree->get_tree(0, $str);
        $this->assign("taxonomys", $taxonomys);
    }

    // 商品删除
    public function delete(){
        if(isset($_GET['id'])){
            $id = I("get.id",0,'intval');
            if ($this->goods_model->where(array('id'=>$id))->save(array('goods_status'=>"-1")) !==false) {
                $this->success("删除成功！");
            } else {
                $this->error("删除失败！");
            }
        }

        if(isset($_POST['ids'])){
            $ids = I('post.ids/a');

            if ($this->goods_model->where(array('id'=>array('in',$ids)))->save(array('goods_status'=>"-1"))!==false) {
                $this->success("删除成功！");
            } else {
                $this->error("删除失败！");
            }
        }
    }

}